package com.service.lotterySystem.service.impl;

import com.alibaba.excel.EasyExcel;
import com.service.config.utils.*;
import com.service.lotterySystem.dao.*;
import com.service.lotterySystem.dto.*;
import com.service.lotterySystem.entity.*;
import com.service.lotterySystem.rabbitmq.MsgProducer;
import com.service.lotterySystem.service.ActivityService;
import com.service.lotterySystem.service.AddressService;
import com.service.lotterySystem.service.HelpService;
import com.service.lotterySystem.service.PrizeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

import static com.service.config.constant.Constant.*;

/**
 * @author ：hjl
 * @date ：Created in 2022/01/11 11:10
 * @description：
 */
@Service
@Slf4j
public class PrizeServiceImpl implements PrizeService {
    @Value("${spring.filePath}")
    String filePath;
    @Value("${spring.fileUrl}")
    String fileUrl;

    @Resource
    private PrizeInfoDao prizeDao;
    @Resource
    private ActivityInfoDao activityDao;
    @Resource
    private JoinInfoDao joinDao;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private ActivityService activityService;
    @Resource
    private HelpService helpService;
    @Resource
    private MsgProducer msgProducer;
    @Resource
    private LogisticsInfoDao logisticsInfoDao;
    private HelpInfoDao helpInfoDao;
    @Resource
    private AddressService addressService;

    /**
     * 手动上传中奖编号
     * @param userId
     * @param prizeDtos
     * @return
     */
    @Override
    public Result addPrizeInfo(String userId, PrizeDto[] prizeDtos) {
        if (prizeDtos.length<0)
        {
            return Result.failure(DATA_FORMAT_WRONG,"未传递有效数据");
        }
        List<PrizeInfo> prizeInfos = prizeDao.queryPrizeByAid(prizeDtos[0].getAId());
        for (PrizeDto prizeDto : prizeDtos) {
            if (prizeDto.getAId()==null || prizeDto.getAId().equals("")
                    || prizeDto.getWinNum()==null)
            {
                return Result.failure(DATA_FORMAT_WRONG,"传递参数有误");
            }

            //判断中奖号码是否重复添加
            boolean flag = prizeInfos.stream().anyMatch(prizeInfo ->
                    prizeInfo.getWinNum().equals(prizeDto.getWinNum())
            );
            if (flag)
            {
                return Result.failure(DATA_FORMAT_WRONG,"该中奖号码："+prizeDto.getWinNum()+"，已存在，请重新添加");
            }

            //新增中奖号码
            PrizeInfo prizeInfo = ModelMapperUtil.strictMap(prizeDto, PrizeInfo.class);
            if (prizeInfo.getWStatus()==null)
            {
                prizeInfo.setWStatus(true);
            }
            prizeInfo.setUploadTime(new Date());
            prizeInfo.setWUpdateTime(new Date());
            prizeInfo.setUpdateOperateId(userId);
            prizeInfo.setAddOperateId(userId);
            prizeInfo.setId(IdUtil.getStringId());

            prizeDao.insert(prizeInfo);
        }
        return Result.ok();
    }

    /**
     * 通过excel上传中奖编号
     * @param file
     * @param aid
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public Result addPrizeInfoWithExcel(MultipartFile file, String aid, String userId) throws Exception {
        // 1.判断文件是否为空
        if (file == null) {
            return Result.failure(UPLOAD_EXCEL_EMPTY, UPLOAD_EXCEL_EMPTY_INFO);
        }
        // 2.判断上传内容是否符合要求
        String fileName = file.getOriginalFilename();
        // 判断是否是excel文件
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return Result.failure(UPLOAD_EXCEL_ERROR, UPLOAD_EXCEL_ERROR_INFO);
        }
        //获取Excel表格数据
        List<UploadPrizeDto> uploadPrizeList = this.batchImport(file,UploadPrizeDto.class,2);
        if(null==uploadPrizeList)
        {
            return Result.failure(FILE_ISNULL,"当前文件无数据");
        }
        //校验Excel数据
        Map<Integer, String> result = checkExcelData(uploadPrizeList);
        //数据有异常,返回错误信息
        if(result.containsKey(0))
        {
            return Result.failure(DATA_FORMAT_WRONG,result.get(0));
        }
        //查询当前活动中所有的中奖号码
        List<PrizeInfo> prizeInfos = prizeDao.queryPrizeByAid(aid);

        //遍历插入数据
        uploadPrizeList.forEach(uploadPrize->{
            //遍历该活动的中奖号码是否与数据库中的号码有重复
            List<PrizeInfo> collect = prizeInfos.stream().filter(prizeInfo ->
                    uploadPrize.getWinNum().equals(prizeInfo.getWinNum())
            ).collect(Collectors.toList());
            //若无重复则添加数据
            if (collect.size()<=0)
            {
                PrizeInfo prizeInfo = ModelMapperUtil.strictMap(uploadPrize, PrizeInfo.class);
                prizeInfo.setId(IdUtil.getStringId());
                prizeInfo.setUploadTime(DateUtils.getNowDate());
                prizeInfo.setAId(aid);
                prizeInfo.setAddOperateId(userId);
                prizeInfo.setWUpdateTime(DateUtils.getNowDate());
                prizeInfo.setUpdateOperateId(userId);
                prizeDao.insert(prizeInfo);
            }
        });
        return Result.ok();
    }

    /**
     * 查询指定活动下所有的中奖人员
     * @param aid
     * @return
     */
    @Override
    public Result queryAllPrizeByAid(String aid) {
        ActivityInfo activityInfo = getEndActivity(aid);
        if (null == activityInfo)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"当前活动不存在");
        }
        if ("1".equals(activityInfo.getIsCurrent()))
        {
            //活动尚未结束
            return Result.failure(PARAMETER_NOT_FOUND,"活动尚未结束");
        }
        if (activityInfo.getIsCalculation() == 1 || activityInfo.getIsCalculation() == 0 ) {
            //活动尚未闭环
            return Result.failure(PARAMETER_NOT_FOUND,"该活动的中奖名单还未开始或计算中,请耐心等待");
        }
        //查询该用户在此活动中的抽奖编号
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid(aid, "");//活动下参加的用户
        if (joinInfos.size() == 0) {
            return Result.failure("还未有参加活动的人员");
        }
        List<UserInfo> userInfoList = userInfoDao.queryUsersOfActivity(aid);
        List<JoinInfo> collect = joinInfos.stream().filter(JoinInfo::getIsStatus).collect(Collectors.toList());//中奖人员
        collect = collect.stream().sorted(Comparator.comparing(JoinInfo::getJScore)).collect(Collectors.toList());//排序
        List<JoinInfoDto> joinInfoDtos = ModelMapperUtil.strictMapList(collect, JoinInfoDto.class);
        joinInfoDtos.forEach(joinInfoDto -> {
            List<UserInfo> collect1 = userInfoList.stream().filter(userInfo -> userInfo.getId().equals(joinInfoDto.getUId())).collect(Collectors.toList());
            String Uname = StringUtils.getStarString(collect1.get(0).getTelphone(),3, 7);
            joinInfoDto.setTelphone(Uname);
        });
        //查询指定活动下所有的中奖人员
        return Result.ok().setData(joinInfoDtos);
    }

    /**
     * 查询该活动下所有中奖用户
     * @param aid
     * @return
     */
    @Override
    public Result queryPrizedUser(String aid ) {

        ActivityInfo activityInfo = getEndActivity(aid);
        if (null==activityInfo)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"当前活动未结束或不存在");
        }

        List<UserInfo> userInfos = userInfoDao.queryPrizedUser(aid,"");
        return Result.ok().setData(userInfos);
    }

    /**
     * 查询指定活动下某个或多个中奖号码的中奖人员
     * @param aid 活动id
     * @param userId 一个或多个中奖号码
     * @return
     */
    @Override
    public Result queryPrizedNumUser(String aid, String userId) {
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid(aid,userId);
        List<LogisticsInfoDto> logisticsInfoDtos = logisticsInfoDao.queryLogisticsInfoByUserId(userId, aid, "", 1);
        JoinInfo joinInfo = joinInfos.stream().findFirst().get();
        JoinAndActivityInfoDto joinAndActivityInfoDto = ModelMapperUtil.strictMap(joinInfo, JoinAndActivityInfoDto.class);
        if (logisticsInfoDtos.size() > 0) {
            joinAndActivityInfoDto.setLNum(logisticsInfoDtos.stream().findFirst().get().getlNum());
        }
        return Result.ok().setData(joinAndActivityInfoDto);
    }

    /**
     * 删除中奖编号
     * @param prizeId
     * @return
     */
    @Override
    public Result deleteById(String prizeId) {
        prizeDao.deleteById(prizeId);
        return Result.ok();
    }

    /**
     * 修改中奖编号
     * @param prizeDto
     * @return
     */
    @Override
    public Result updatePrizeInfo(PrizeDto prizeDto,String uid) {
        PrizeInfo prizeInfo = ModelMapperUtil.strictMap(prizeDto, PrizeInfo.class);
        prizeInfo.setWUpdateTime(DateUtils.getNowDate());
        prizeInfo.setUpdateOperateId(uid);
        prizeDao.update(prizeInfo);
        return Result.ok();
    }

    @Override
    public Result exportAllPrizeInfo(String aid) {
        //校验该活动是否存在
        QueryActivityInfoDto activityDto = activityService.queryById(aid);
        if (null == activityDto)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"未查询到该活动");
        }
        //校验该活动是否有中奖信息
        List<PrizeInfo> prizeInfos = prizeDao.queryPrizeByAid(aid);
        if (null == prizeInfos || prizeInfos.size()<=0)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"该活动尚未上传中奖信息");
        }
        List<ExportPrizeDto> exportPrizeDtos=new ArrayList<>();
        for (PrizeInfo prizeInfo : prizeInfos) {
            ExportPrizeDto exportPrizeDto = ModelMapperUtil.strictMap(prizeInfo, ExportPrizeDto.class);
            exportPrizeDto.setAName(activityDto.getAName());
            if (prizeInfo.getWStatus()==null || prizeInfo.getWStatus() == false) {
                exportPrizeDto.setWStatus(0);
            } else {
                exportPrizeDto.setWStatus(1);
            }
            exportPrizeDtos.add(exportPrizeDto);
        }

//        String dateTime = DateUtils.dateTime(); 年月日
        Long dateTime = System.currentTimeMillis();
        EasyExcel.write(filePath+"中奖信息_"+dateTime+".xlsx",ExportPrizeDto.class).sheet("中奖信息").doWrite(exportPrizeDtos);
        return Result.ok().setData(filePath+"中奖信息_"+dateTime+".xlsx");
    }

    /**
     * 管理员根据活动id生成中奖名单（只能生成一次）
     * @param aid
     * @param userDto
     * @return
     */
    @Override
    public Result addPrizeInfoWith(String aid, OperateUserInfo userDto) {
        ActivityInfo activityInfo = activityDao.queryById(aid);
        if (activityInfo == null)
        {
            return Result.failure("该活动不存在");
        }
        if (activityInfo.getAType() == 1 || activityInfo.getAType() == 2) {
            return Result.failure("该活动还在计算或已计算完毕，不能重新计算");
        }
        if (activityInfo.getAStatus()) {
            return Result.failure("该活动未结束，不能重新计算");
        }
        if (activityInfo.getIsCalculation() == 2) {
            return Result.failure("该活动还在计算或已计算完毕，不能重新计算");
        }
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid(aid, "");
        joinInfos.forEach(joinInfo -> joinInfo.setIsStatus(false));
        if (joinInfos.size() >0) {
            joinDao.insertOrUpdateBatch(joinInfos);
        }
        List<UserInfo> userInfoList = userInfoDao.queryUsersOfActivity(aid);
        if (joinInfos == null || joinInfos.size()<=0 || userInfoList==null || userInfoList.size()<=0)
        {
            return Result.failure("当前活动暂无人员参加");
        }

        List<JoinInfo> collect = joinInfos.stream().filter(joinInfo -> joinInfo.getShareCount() >= 5 ).collect(Collectors.toList()); //筛选元宝个数大于5个的
        collect = collect.stream().sorted(Comparator.comparing(JoinInfo::getShareCount).reversed().thenComparing(JoinInfo::getJUpdateTime)).collect(Collectors.toList()); //元宝个数排序

        //中奖用户集合
        List<JoinInfo> joinInfos1 = new ArrayList<>();
        //幸运奖用户集合
        List<JoinInfo> luckInfos = new ArrayList<>();


        for (int i = 0;i < collect.size();i++) { //排名
            collect.get(i).setJScore(i+1);
            if (i < 30) {
                joinInfos1.add(collect.get(i));
            }
            if (collect.get(i).getJScore().toString().contains("22")) {
                collect.get(i).setIsLucky(true);
                luckInfos.add(collect.get(i));
            }
        }
        for (int i = 0 ;i < joinInfos1.size();i++) {
            if (i < 5) {
                joinInfos1.get(i).setIsStatus(true);
                joinInfos1.get(i).setIsCount(true);
                joinInfos1.get(i).setJLevel(1);
                joinInfos1.get(i).setPrizeName("moza手机云台");
            }else if (i< 20) {
                joinInfos1.get(i).setIsStatus(true);
                joinInfos1.get(i).setIsCount(true);
                joinInfos1.get(i).setJLevel(2);
                joinInfos1.get(i).setPrizeName("华为手环");
            }else {
                joinInfos1.get(i).setIsStatus(true);
                joinInfos1.get(i).setIsCount(true);
                joinInfos1.get(i).setJLevel(3);
                joinInfos1.get(i).setPrizeName("华为智能热水杯");
            }
        }
        if (collect.size() >0) {
            joinDao.insertOrUpdateBatch(collect);
        }
        if (joinInfos1.size() > 0) {
            joinDao.insertOrUpdateBatch(joinInfos1);//更新中奖人员所属奖项以及等级
        }
        ActivityInfo activityInfo1 = new ActivityInfo();
        activityInfo1.setId(aid);
        activityInfo1.setAType(0);
        activityInfo1.setAStatus(false);
        activityInfo1.setIsCurrent("0");
        activityInfo1.setIsCalculation(2);

        //给中奖用户发送短信
        joinInfos1.forEach(joinInfo -> {
            msgProducer.sendSms(joinInfo.getUId(),aid,0);
        });

        //给幸运奖用户发送短信
        luckInfos.forEach(luckInfo -> {
            msgProducer.sendSms(luckInfo.getUId(),aid,0);
        });
        activityInfo.setAStatus(false);
        activityInfo.setIsCalculation(2);
        activityDao.update(activityInfo);
        return Result.ok();
    }

    @Override
    public Result exportPrizeList(String aid) {
        ActivityInfo activityInfo = activityDao.queryById(aid);
        if (activityInfo == null || activityInfo.getAType() != 0)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"活动未结束");
        }
        //查询活动下的中奖信息
        List<JoinInfoDto> joinInfoDtos = (List<JoinInfoDto>) this.queryPrizedUserDetailByAid(aid).getData();
        if (joinInfoDtos==null || joinInfoDtos.size()<=0)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"未查询到中奖信息");
        }

        List<ExportPrizeInfoDto> exportPrizeInfoDtos = new ArrayList<>();

        //查询该活动下所有的物流单号
        List<LogisticsInfo> logisticsInfos = logisticsInfoDao.queryAllLogicsticsOfActivity(aid);
        //查询该活动下所有的收货地址
//        List<ReceiveAddressDto> receiveAddressDtos = addressService.queryPrizedUserAddressByAid(aid);

        joinInfoDtos.forEach(joinInfoDto -> {
            ExportPrizeInfoDto exportPrizeInfoDto = new ExportPrizeInfoDto();
            //活动信息
            exportPrizeInfoDto.setAId(aid);
            exportPrizeInfoDto.setAName(activityInfo.getAName());
            //用户信息
            exportPrizeInfoDto.setUId(joinInfoDto.getUId());
            exportPrizeInfoDto.setNickName(joinInfoDto.getUName());
            //地址信息
            if (joinInfoDto.getAddressDto() != null)
            {
                exportPrizeInfoDto.setRId(joinInfoDto.getAddressDto().getId());
                exportPrizeInfoDto.setReceiveAddress(joinInfoDto.getAddressDto().getrSpecificAddress());
            }

            exportPrizeInfoDto.setTel(joinInfoDto.getTelphone());
            exportPrizeInfoDto.setNickName(joinInfoDto.getUName());
            exportPrizeInfoDto.setShareCount(joinInfoDto.getShareCount());

            if (joinInfoDto.getAddressDto() != null)
            {
                if (joinInfoDto.getAddressDto().getrName() != null && !joinInfoDto.getAddressDto().getrName().equals(""))
                {
                    //设置收件人姓名
                    exportPrizeInfoDto.setUName(joinInfoDto.getAddressDto().getrName());
                }

                if (joinInfoDto.getAddressDto().getrTel() != null && !joinInfoDto.getAddressDto().getrTel().equals(""))
                {
                    //设置收件人手机号
                    exportPrizeInfoDto.setTelphone(joinInfoDto.getAddressDto().getrTel());
                }
            }

            //设置中奖用户的中奖信息
            Integer jLevel = joinInfoDto.getJLevel();
            if (null != jLevel)
            {
                switch (jLevel)
                {
                    case 1:
                        exportPrizeInfoDto.setPrizeInfo("一等奖");
                        break;
                    case 2:
                        exportPrizeInfoDto.setPrizeInfo("二等奖");
                        break;
                    case 3:
                        exportPrizeInfoDto.setPrizeInfo("三等奖");
                        break;
                    default:
                        break;
                }
            }
            if (joinInfoDto.getIsLucky() != null && joinInfoDto.getIsLucky()==true)
            {
                if (exportPrizeInfoDto.getPrizeInfo()==null || exportPrizeInfoDto.getPrizeInfo().equals(""))
                {
                    //未获取其他奖项，只有幸运奖
                    exportPrizeInfoDto.setPrizeInfo("幸运奖");
                }else {
                    //既获取其他奖项，又获得幸运奖
                    exportPrizeInfoDto.setPrizeInfo(exportPrizeInfoDto.getPrizeInfo()+"、幸运奖");
                }
            }

            //查询是否已经填写了物流单号
            if (logisticsInfos!=null && logisticsInfos.size()>0)
            {
                Optional<LogisticsInfo> first = logisticsInfos.stream().filter(logisticsInfo ->
                        logisticsInfo.getUId().equals(joinInfoDto.getUId())
                ).findFirst();
                first.ifPresent(logisticsInfo -> exportPrizeInfoDto.setLNum(logisticsInfo.getLNum()));
            }

            exportPrizeInfoDtos.add(exportPrizeInfoDto);
        });

        long millis = System.currentTimeMillis();
        EasyExcel.write(filePath+"活动中奖名单_"+millis+".xlsx", ExportPrizeInfoDto.class).sheet().doWrite(exportPrizeInfoDtos);
        return Result.ok().setData(fileUrl+"活动中奖名单_"+millis+".xlsx");
    }

    /**
     * 查询指定活动下所有的中奖人员、物流、地址、活动详情
     * @param aid
     * @return
     */
    @Override
    public Result queryPrizedUserDetailByAid(String aid) {
        ActivityInfo activityInfo = getEndActivity(aid);
        if (null == activityInfo)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"当前活动不存在");
        }
        if ("1".equals(activityInfo.getIsCurrent()))
        {
            //活动尚未结束
            return Result.failure(PARAMETER_NOT_FOUND,"活动尚未结束");
        }
        if (activityInfo.getIsCalculation() == 1 || activityInfo.getIsCalculation() == 0 ) {
            return Result.failure(PARAMETER_NOT_FOUND,"该活动的中奖名单还未开始或计算中,请耐心等待");
        }
        //查询该用户在此活动中的抽奖编号
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid(aid, "");//活动下参加的用户
        if (joinInfos.size() == 0) {
            return Result.failure("还未有参加活动的人员");
        }
        //中奖人员
        List<JoinInfo> collect = joinInfos.stream().filter(JoinInfo::getIsStatus).collect(Collectors.toList());
        List<JoinInfoDto> joinInfoDtos = new ArrayList<>();
        if (collect.size()<=0)
        {
            return Result.ok().setData(joinInfoDtos);
        }
        joinInfoDtos = ModelMapperUtil.strictMapList(collect, JoinInfoDto.class);
        //查询joinInfo中的详细用户和活动
        UserInfo userInfo=new UserInfo();
        List<UserInfo> userInfos = userInfoDao.queryAll(userInfo);
        if (userInfos==null || userInfos.size()<=0)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"用户表中未查询到注册用户");
        }
        //为中奖信息补充详细信息
        //查询物流信息
        List<LogisticsInfoDto> logisticsInfoDtos = logisticsInfoDao.queryLogisticsInfoByUserId("", aid, "", null);
        //查询中奖用户默认收货地址
        List<ReceiveAddressDto> addressDtos = addressService.queryPrizedUserAddressByAid(aid);

        joinInfoDtos.forEach(joinInfoDto -> {
            //默认页面物流单号信息不可修改
            joinInfoDto.setIsModify(true);
            //匹配中奖用户详情
            Optional<UserInfo> first = userInfos.stream().filter(userInfo1 ->
                    userInfo1.getId().equals(joinInfoDto.getUId())
            ).findFirst();
            if(first.isPresent())
            {
                joinInfoDto.setTelphone(first.get().getTelphone());
                joinInfoDto.setUserInfoDto(ModelMapperUtil.strictMap(first.get(),UserInfoDto.class));
            }

            //匹配用户物流单号
            if (null != logisticsInfoDtos && logisticsInfoDtos.size()>0)
            {
                boolean flag = logisticsInfoDtos.stream().anyMatch(logisticsInfoDto ->
                        joinInfoDto.getTelphone().equals(logisticsInfoDto.getTelphone())
                );
                if (flag)
                {

                    Optional<LogisticsInfoDto> first1 = logisticsInfoDtos.stream().filter(logisticsInfoDto ->
                            joinInfoDto.getTelphone().equals(logisticsInfoDto.getTelphone())
                    ).findFirst();
                    joinInfoDto.setLogisticsInfoDto(first1.get());
                }
            }

            //匹配用户默认收货地址(规则：有物流单号则查询物流单号绑定的地址，若没有物流单号则查询默认的收货地址)
            if (null == joinInfoDto.getLogisticsInfoDto())
            {
                //没有查询到物流单号，使用默认地址
                if (addressDtos !=null && addressDtos.size()>0)
                {
                    Boolean flag= addressDtos.stream().anyMatch(receiveAddressDto ->
                            receiveAddressDto.getuId().equals(joinInfoDto.getUId()) && receiveAddressDto.getrType()
                    );
                    if(flag)
                    {
                        ReceiveAddressDto receiveAddressDto1 = addressDtos.stream().filter(receiveAddressDto ->
                                receiveAddressDto.getuId().equals(joinInfoDto.getUId())
                        ).findFirst().get();
                        joinInfoDto.setAddressDto(receiveAddressDto1);
                    }
                }
            }else if (null != joinInfoDto.getLogisticsInfoDto())
            {
                //查询到物流单号，使用物流单号绑定的收货地址
                Optional<ReceiveAddressDto> first1 = addressDtos.stream().filter(receiveAddressDto ->
                        receiveAddressDto.getId().equals(joinInfoDto.getLogisticsInfoDto().getR_id())
                ).findFirst();
                first1.ifPresent(joinInfoDto::setAddressDto);
            }
        });

        return Result.ok().setData(joinInfoDtos);
    }

    @Override
    public Result queryAllPrizeByAid(String aid, String userId) {
        ActivityInfo activityInfo = getEndActivity(aid);
        if (null == activityInfo)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"当前活动不存在");
        }
        if ("1".equals(activityInfo.getIsCurrent()))
        {
            //活动尚未结束
            return Result.failure(PARAMETER_NOT_FOUND,"活动尚未结束");
        }
        if (activityInfo.getIsCalculation() == 1 || activityInfo.getIsCalculation() == 0 ) {
            //活动尚未闭环
            return Result.failure(PARAMETER_NOT_FOUND,"该活动的中奖名单还未开始或计算中,请耐心等待");
        }
        //查询该用户在此活动中的抽奖编号
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid(aid, "");//活动下参加的用户
        if (joinInfos.size() == 0) {
            return Result.failure("还未有参加活动的人员");
        }
        List<UserInfo> userInfoList = userInfoDao.queryUsersOfActivity(aid);
        List<JoinInfo> collect = joinInfos.stream().filter(JoinInfo::getIsStatus).collect(Collectors.toList());//中奖人员
        collect = collect.stream().sorted(Comparator.comparing(JoinInfo::getJScore)).collect(Collectors.toList());//排序
        List<JoinInfoDto> joinInfoDtos = ModelMapperUtil.strictMapList(collect, JoinInfoDto.class);
        joinInfoDtos = joinInfoDtos.stream().filter(joinInfoDto -> joinInfoDto.getUId().equals(userId)).collect(Collectors.toList());
        joinInfoDtos.forEach(joinInfoDto -> {
            List<UserInfo> collect1 = userInfoList.stream().filter(userInfo -> userInfo.getId().equals(joinInfoDto.getUId())).collect(Collectors.toList());
            String Uname = StringUtils.getStarString(collect1.get(0).getTelphone(),3, 7);
            joinInfoDto.setTelphone(Uname);
        });
        //查询指定活动下所有的中奖人员
        return Result.ok().setData(joinInfoDtos);
    }

    public ActivityInfo getEndActivity(String aid)
    {
        ActivityInfo activityInfo = activityDao.queryById(aid);
        if (null == activityInfo || activityInfo.getAType()==1 || activityInfo.getAType()==2)
        {
            return null;
        }
        return activityInfo;
    }

    public <T> List<T> batchImport(MultipartFile file,Class<T> t,int startLine) throws Exception {
        /*
         * 判断文件名的合法性
         * 判断文件是2003版or2007版
         */
        String fileName = file.getOriginalFilename();
        String[] fullName = null;
        if (fileName != null) {
            fullName = fileName.split("\\.");
        }
        //log.info(fullName[1]);
        boolean isExcel2003 = true;
        if (fullName != null) {
            String suffix = fullName[1];
            if (!suffix.equals("xls") && !suffix.equals("xlsx")) {
                throw new Exception("上传不正确");
            }
            if (suffix.equals("xlsx")) {
                isExcel2003 = false;
            }
        }
        InputStream iStream = file.getInputStream(); //IO流
        Workbook workbook = null; //创建工作簿
        try {
            if (isExcel2003) {
                workbook = new HSSFWorkbook(iStream); //2003版
            } else {
                workbook = new XSSFWorkbook(iStream); //2007版
            }
        }catch (Exception e)
        {
            return null;
        }
        //将文件存储到本地
        String savePath = null;
        try {
            savePath = filePath + fileName;
            log.info(savePath);
            OutputStream os = new FileOutputStream(savePath); // 保存到当前路径savePath
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("File saving error !");
            e.printStackTrace();
        }
        Workbook workbook2 = WorkbookFactory.create(file.getInputStream());
        Sheet sheet = workbook2.getSheetAt(0);
        ExcelUtil<T> util = new ExcelUtil<>(t);
        List<T> uploadProgrammeDtoList = util.importExcel(sheet.getSheetName(), workbook2, startLine);
        return uploadProgrammeDtoList;
    }

    public Map<Integer,String> checkExcelData(List<UploadPrizeDto> prizeDtoList)
    {
        Map<Integer,String> result=new HashMap<>();
        for (int i=0;i<prizeDtoList.size();i++) {
            UploadPrizeDto uploadPrizeDto = prizeDtoList.get(i);
            if(uploadPrizeDto.getAName()==null || uploadPrizeDto.getAName().equals("") ||
                    uploadPrizeDto.getWinNum()==null || uploadPrizeDto.getWinNum().equals("")||
                    uploadPrizeDto.getWStatus()==null)
            {
                result.put(0,"第"+i+"条数据为空");
                return result;
            }
        }
        result.put(1,"");
        return result;
    }
}
